// 实现发布订阅/node.js中的EventEmitter的实现
class EventEmitter {
    events = {}
    // 事件注册最大限制
    maxNum = 10

    emit(eventName, ...args) {
        const events = this.events[eventName]
        if(events) {
            events.forEach(callback => callback(...args))
        }
    }
    
    on(eventName, callback) {
        if(!this.events[eventName]) {
            this.events[eventName] = []
        }
        // 最多加入多少事件
        if (this.events[ev].length < this.maxNum) {
            this.events[ev].push(callback)
        }
    }

    off(eventName, callback) {
        if(eventName && this.events[eventName]) {
            const fns = this.events[eventName]
            // const newCallbacks = fns.filter(fn => fn != callback && fn.initialCallback != callback /* 用于once的取消订阅 */)
            const newCallbacks = fns.filter(fn => fn != callback)
            this.events[eventName] = newCallbacks
        }
    }

    once(eventName, callback) {
        const wrap = (...args) => {
            callback(...args)
            this.off(eventName, wrap)
        }
        // wrap.initialCallback = callback
        this.on(eventName, wrap)
    }

    setMaxListeners(maxNum) {
        this.maxNum = maxNum
    }
}